<?php
namespace App\Admin\Extensions;
use Encore\Admin\Grid;
use Illuminate\Support\Arr;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\WaybillExport;

class WaybillExporter extends AbstractExporter
{
    // protected $head = [];
    // protected $body = [];
    // protected $fields = [];
    // protected $content = [];
    // public function setAttr($head, $fields, $body=[] ){
    //     $this->head = $head;
    //     $this->fields = $fields;
    //     $this->body = $body;
    // }

    public function export()
    {
        $filename = sprintf("运单列表-%s",date('Y-m-d')).'.xlsx';

        $data = $this->getData();

        try {
            $res = Excel::store(new WaybillExport($data, $filename), 'waybill/'.$filename, 'admin', \Maatwebsite\Excel\Excel::XLSX);
        }
        catch (\Exception $e) {
            return response()->error('导出失败:'.$e->getMessage())->refresh();
        }

        if (!$res)
        {
            return response()->error('导出失败')->refresh();
        }

        // $url = env('APP_URL').'/upload/zhongtong/'.$filename;
        $url = public_path('upload').'/waybill/'.$filename;

        $output = file_get_contents($url);

        $headers = [
            'Content-Encoding'    => 'UTF-8',
            'Content-Type'        => 'text/csv;charset=UTF-8',
            'Content-Disposition' => "attachment; filename=\"$filename\"",
        ];
        response(rtrim($output, "\n"), 200, $headers)->send();
        exit;

        // $headers = [
        //     'Content-Encoding'    => 'UTF-8',
        //     'Content-Type'        => 'text/csv;charset=UTF-8',
        //     'Content-Disposition' => "attachment; filename=\"$filename\"",
        // ];
        // dd($url);
        // $down_files = response()->download($url, $filename);
        // dd($down_files);
        // return $down_files;

    }

    // public function export()
    // {
    //     $filename = sprintf("导出订单-%s",date('Y-m-d'));
    //     $data = $this->getData();
    //     $this->body = $this->getExportData($data);
    //     // dd($data);
    //     Excel::create($filename, function($excel) {
    //         foreach ($this->body as $key => $body) {
    //             // $this->content = $body['data'];
    //             $excel->sheet($body, function($sheet) {
    //                 $sheet->setWidth(array(
    //                     'B'     =>  12,
    //                     'E'     =>  12,
    //                     'F'     =>  22,
    //                 ));
    //                 $sheet->row(1, $this->head);
    //                 // 这段逻辑是从表格数据中取出需要导出的字段
    //                 // $amount_sum = array_sum(array_column($this->content, 'amount'));
    //                 // $this->content[] = [
    //                 //     'order_no' => '',
    //                 //     'address_ship_id' => '',
    //                 //     'weight' => '',
    //                 //     'volume_size' => '',
    //                 //     'amount'=> "总计:".$amount_sum,
    //                 // ];

    //                 $rows = collect($this->content)->map(function ($item) {
    //                     return array_only($item, $this->fields);
    //                 });
    //                 $sheet->rows($rows);

    //             });
    //         }

    //     })->export('xls');
    // }

    // protected function getExportData($data){
    //     // dd($data);
    //     try {
    //         // $region_list = [];
    //         // $tmp = Region::select('region_name','id')->get()->toArray();
    //         // foreach ($tmp as $v) $region_list[$v['id']] = $v['region_name'];
    //         // $region_list = array_unique($region_list);

    //         $_data = [];
    //         $goods_ids = [];
    //         foreach ($data as $key => $value) {
    //             // if (!$value['address_ship_id']) continue;
    //             // $value['address_ship_id'] = $region_list[$value['address_ship_id']];
    //             // $_data[$value['company_id']][] = $value;
    //             // $value['weight'] = str_replace('..', '.', $value['weight']);

    //              // 'order_no','goods_name', 'store_name', 'subscriber', 'contact','delivery_type', 'delivery_time','delivery_address', 'status', 'voucher', 'cashier', 'making', 'remark', 'created_at'
    //             $_data_ = [];
    //             $_data_['order_no'] = $value['order_no'];
    //             $_data_['goods_name'] = $value['goods_id'];
    //             $_data_['store_name'] = $value['store_id'];
    //             $_data_['subscriber'] = $value['subscriber'];
    //             $_data_['contact'] = $value['contact'];
    //             $_data_['delivery_type'] = ($value['delivery_type']=='oneself') ? '自提' : '配送';
    //             $_data_['delivery_time'] = date('Y-m-d H:i', strtotime($value['delivery_time']));
    //             $_data_['delivery_address'] = $value['delivery_address'] ? $value['delivery_address'] : '';
    //             $_data_['status'] = $value['status'];
    //             $_data_['voucher'] = $value['voucher'];
    //             $_data_['cashier'] = $value['cashier'];
    //             $_data_['making'] = $value['making'];
    //             $_data_['remark'] = $value['remark'];
    //             $_data_['created_at'] = $value['created_at'];

    //             $_data[] = $_data_;
    //         }

    //         // dd($data,$_data, array_column($_data, 'goods_name'));
    //         $goodsIds = array_filter(array_unique(array_column($_data, 'goods_name')));
    //         $_goods = [];
    //         if ($goodsIds)
    //         {
    //             $goods = Goods::select('name','goods_id', 'images')->whereIn('goods_id',$goodsIds)->get()->toArray();
    //             foreach ((array)$goods as $key => $value)
    //             {
    //                 if (!$value) continue;
    //                 $_goods[$value['goods_id']] = $value['name'];
    //             }
    //         }

    //         $_store = [];
    //         $storeIds = array_filter(array_unique(array_column($_data, 'store_name')));
    //         if ($storeIds)
    //         {
    //             $store = Store::select('store_name','store_id')->whereIn('store_id',$storeIds)->get()->toArray();
    //             foreach ((array)$store as $key => $value)
    //             {
    //                 if (!$value) continue;
    //                 $_store[$value['store_id']] = $value['store_name'];
    //             }
    //         }
    //         // dd($_data, $goodsIds, $storeIds);

    //         $status_name = [0=>'待处理', 1=>'已提货', 2=>'已指派', 3=>'制作中', 4=>'已完成', 5=>'已作废'];

    //         // 职位: 1、管理员 2、制单人 3、收银员 4、制作师

    //         $_voucher = [];
    //         $voucherIds = array_filter(array_unique(array_column($_data, 'voucher')));
    //         if ($voucherIds)
    //         {
    //             $voucher = Employee::select('id', 'name')->where('position', 2)->whereIn('id', $voucherIds)->get()->toArray();
    //             foreach ((array)$voucher as $key => $value)
    //             {
    //                 if (!$value) continue;
    //                 $_voucher[$value['id']] = $value['name'];
    //             }
    //         }

    //         $_cashier = [];
    //         $cashierIds = array_filter(array_unique(array_column($_data, 'voucher')));
    //         if ($cashierIds)
    //         {
    //             $cashier = Employee::select('id', 'name')->where('position', 2)->whereIn('id', $cashierIds)->get()->toArray();
    //             foreach ((array)$cashier as $key => $value)
    //             {
    //                 if (!$value) continue;
    //                 $_cashier[$value['id']] = $value['name'];
    //             }
    //         }

    //         $_making = [];
    //         $makingIds = array_filter(array_unique(array_column($_data, 'making')));
    //         if ($makingIds)
    //         {
    //             $making = Employee::select('id', 'name')->where('position', 2)->whereIn('id', $makingIds)->get()->toArray();
    //             foreach ((array)$making as $key => $value)
    //             {
    //                 if (!$value) continue;
    //                 $_making[$value['id']] = $value['name'];
    //             }
    //         }

    //         $result = [];
    //         foreach ($_data as $key => $value) {
    //             $result[$key] = $value;
    //             $result[$key]['goods_name'] = $_goods[$value['goods_name']];
    //             $result[$key]['store_name'] = $_store[$value['store_name']];
    //             $result[$key]['status'] = $status_name[$value['status']];
    //             $result[$key]['voucher'] = isset($_voucher[$value['voucher']]) ? $_voucher[$value['voucher']] : '';
    //             $result[$key]['cashier'] = isset($_cashier[$value['cashier']]) ? $_cashier[$value['cashier']] : '';
    //             $result[$key]['making'] = isset($_making[$value['making']]) ? $_making[$value['making']] : '';

    //         }
    //         // dd($result);
    //     } catch (\Exception $exception) {
    //         dd($exception->getMessage(), $_data_);
    //     }
    //     return $result;
    // }


    // /**
    //  * Remove indexed array.
    //  *
    //  * @param array $row
    //  *
    //  * @return array
    //  */
    // protected function sanitize(array $row)
    // {
    //     return collect($row)->reject(function ($val) {
    //         return is_array($val) && !Arr::isAssoc($val);
    //     })->toArray();
    // }

    // /**
    //  * @param $row
    //  * @param string $fd
    //  * @param string $quot
    //  *
    //  * @return string
    //  */
    // protected static function putcsv($row, $fd = ',', $quot = '"')
    // {
    //     $str = self::strIconv(implode(',', $row),'utf-8','gbk')."\n";
    //     return $str;
    // }

    // protected static function strIconv($str,$from='GBK',$to='utf-8'){
    //     return iconv("$from","$to//TRANSLIT",$str);
    // }
}